package SVN::TeamTools::Web::DataProvider;

use warnings;
use strict;
use Carp;
use Error qw(:try);

use SVN::TeamTools::Store::Config;

use Module::Pluggable require=>1, search_path => [ 'SVN::TeamTools::Plugins' , 'SVN::TeamTools::Store' ];

use Apache2::RequestRec ();
use Apache2::RequestIO ();
use Apache2::Const -compile => qw(OK);

use CGI;
use URI::Escape;
use JSON;

use Data::Dumper;

my $conf;
my $logger;
BEGIN { $conf = SVN::TeamTools::Store::Config->new(); $logger = $conf->{logger}; }

sub handler {
	my $_h = shift;
	my $cgi = CGI->new();
	my $json = JSON->new();
	my @rawcgi = $cgi->param('POSTDATA');
	my $jsonparam = "";
	foreach my $l (@rawcgi) {
		$jsonparam = $jsonparam . $l . " ";
	}
	my $param = $json->decode($jsonparam);
	my $action = $param->{action};
	my $result;

	$_h->content_type('text/plain');

	if ($action =~ /get.config.full/) {
		$_h->print ($json->encode($conf->getData()));
	} elsif ($action =~ /store.config/) {
		my $res = $json->encode($conf->store (data => $param->{data}));
		$conf = SVN::TeamTools::Store::Config->new(); $logger = $conf->{logger};
		$_h->print ($res);
	} else {
		foreach my $plugin (plugins()) {
			next unless ($plugin->hasAction(action => $action));
			my $res = $json->encode($plugin->getData(action => $action, param => $param));
			$_h->print ($res);
			last;
		}
	}

	return Apache2::Const::OK;
}
1;
